<?php

namespace App\Http\Controllers\Purchase;

use App\Http\Controllers\BaseController;
use App\Http\Controllers\Chanjet\TplusCommonController;
use App\Http\Validate\Purchase\PurchasePayOrderApproveSub as PurchasePurchasePayOrderApproveSub;
use App\Models\Custom\Custom;
use App\Models\Purchase\ApprovalHistory;
use App\Models\Purchase\PurchaseAgreement;
use App\Models\Purchase\PurchaseOrder;
use App\Models\Purchase\PurchaseOrderProcess;
use App\Models\Purchase\PurchasePayOrderApprove;
use App\Models\Purchase\PurchasePayOrderApproveSub;
use App\Models\Purchase\PurchasePayOrderNew;
use App\Models\Purchase\PurchaseWarehousingOrderwithpay;
use App\Services\Balance\Balance;
use App\Services\Chanjet\ChanjetRequest;
use App\Services\Common\Common;
use App\Services\Common\SnCode;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 付款列表
 */
class PurchasePayOrderApproveController extends BaseController
{
    /**
     * 付款列表
     */
    public function getorderlist(Request $request)
    {


        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        // if ($this->mangerinfo['utype'] == 4) {
        //     $manger_id = 0; //查询所有订单
        // }


        $list = PurchasePayOrderApprove::getList($request, $cpid, $this->mangerinfo);


        foreach($list['list'] as &$val){
            $order_ids_arr=explode(',',$val['order_ids']);
            $pa_ids=PurchaseOrder::where(['cpid'=>$cpid])->whereIn('id',$order_ids_arr)->groupBy('pa_id')->pluck('pa_id')->toArray();

            $contract_filepath_list=PurchaseAgreement::where(['cpid'=>$cpid])->whereIn('id',$pa_ids)->pluck('contract_filepath')->toArray();

            foreach($contract_filepath_list as &$v){
                $v=json_decode($v,true);


            }
            $contract_payment_info=array_merge($contract_filepath_list,json_decode($val['custom']['payment_info'],true));


            // print_r($contract_payment_info);exit;
            // $val['contract_payment_info']=$contract_payment_info;

            $val['contract_filepath_list']=$contract_filepath_list;
            $val['payment_info']=json_decode($val['custom']['payment_info'],true);

        }




        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 审核取消
     */
    public function doauditcancel(Request $request)
    {

        $id = $request->id;
        //        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];

        $payorderinfo = PurchasePayOrderApprove::where([
            'id' => $id,
            'cpid' => $cpid,
        ])->first();

        if (empty($payorderinfo)) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }
        if ($payorderinfo->audit_status > 2) {
            return response()->json(['code' => '001', 'msg' => '订单状态不能撤审']);
        }
        $approvalinfo = DB::table('order_approvals')
            ->where([
                'order_id' => $id,
                'type' => 'purchase_pay_order_approve',
            ])
            ->orderBy('id', 'desc')
            ->first();

        DB::beginTransaction();
        try {
            //
            PurchasePayOrderApprove::where([
                'id' => $id,
                'cpid' => $cpid,
                'manger_id' => $manger_id,
            ])->update(['audit_status' => 5]);
            DB::table('order_approvals')
                ->where([
                    'order_id' => $id,
                    'type' => 'purchase_pay_order_approve',
                    'id' => $approvalinfo->id,
                ])
                ->update(['is_completed' => 1, 'current_step_id' => 0]);
            DB::table('approval_histories')
                ->insert([
                    'order_id' => $id,
                    'type' => 'purchase_pay_order_approve',
                    'step_id' => $approvalinfo->current_step_id,
                    'approver_id' => 0,
                    'status' => 'revoked',
                ]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核取消操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '补货单审核取消成功']);
    }

    /**
     * 审核通过
     */
    public function doauditsuccess(Request $request)
    {

        $validatedData = $request->validate([
            'id' => 'required|integer',
        ]);

        $id = intval($validatedData['id']); // 确保 id 是整数

        //        $ids = is_array($ids) ? $ids : (is_array(json_decode($ids, true)) ? json_decode($ids, true) : []);

        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];

        $payorderinfo = PurchasePayOrderApprove::where([
            'id' => $id,
            'cpid' => $cpid,
        ])->first();
        if (empty($payorderinfo)) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }
        // 检查操作权限
        if (($payorderinfo->audit_status == 1 && $payorderinfo->approve_id1 != $manger_id) || ($payorderinfo->audit_status == 2 && $payorderinfo->approve_id2 != $manger_id)) {
            return response()->json(['code' => '001', 'msg' => '没有操作权限']);
        }
        // 查询当前审批信息
        $approvalinfo = DB::table('order_approvals')
            ->where([
                'order_id' => $id,
                'type' => 'purchase_pay_order_approve',
            ])
            ->orderBy('id', 'desc')
            ->first();
        //查询下一级审批
        $approval_nextStep = DB::table('approval_steps')
            ->where('flow_id', '=', 1)
            ->where('step_order', '>', $approvalinfo->current_step_id)
            ->orderBy('step_order', 'asc')
            ->first();

        $pay_sn_code = SnCode::getSnCode('PPOA_');
        DB::beginTransaction();
        try {
            //
            if ($approval_nextStep) {
                DB::table('order_approvals')
                    ->where('id', '=', $approvalinfo->id)
                    ->update(['current_step_id' => $approval_nextStep->step_order]);
                // 更新订单审批状态
                PurchasePayOrderApprove::where('id', '=', $id)
                    ->update(['audit_status' => 2]);
            } else {
                // 所有步骤已完成
                DB::table('order_approvals')
                    ->where('id', '=', $approvalinfo->id)
                    ->update(['is_completed' => 1]);
                // 更新订单审批状态
                PurchasePayOrderApprove::where('id', '=', $id)
                    ->update(['audit_status' => 3]);
                $order_list = json_decode($payorderinfo->order_list, true);


                //入库付款对账单
                $datawp = [
                    'cpid' => $cpid,
                    'manger_id' => $manger_id,
                    'type' => 2,
                    'pay_money' => $payorderinfo->pay_money,
                    'pay_sn_code' => $payorderinfo->pay_sn_code,
                    'custom_id'=>PurchaseOrder::where(['id'=>$order_list[0]['id']])->value('custom_id'),
                    'create_at' => time(),
                    'update_at' => time(),
                ];
                PurchaseWarehousingOrderwithpay::create($datawp);

                // //审批通过后增加付款单
                // $datapay = [
                //     'cpid' => $cpid,
                //     'manger_id' => $manger_id,
                //     'approve_id' => $payorderinfo->id, //关联ID
                //     'pay_sn_code' => $pay_sn_code,
                //     'pay_order_date' => time(),
                //     'custom_id' => $payorderinfo->custom_id, //供应商名称
                //     'company_name' => $payorderinfo->company_name, //供应商名称
                //     'pa_settle_company_id' => $payorderinfo->pa_settle_company_id, //结算公司
                //     'pa_settle_company_name' => $payorderinfo->pa_settle_company_name, //结算公司
                //     'settle_model' => $payorderinfo->settle_model, //结算方式
                //     'contacts' => $payorderinfo->contacts, //账户名称
                //     'pay_money' => $payorderinfo->pay_money,
                //     'settle_model'=>$payorderinfo->settle_model,
                //     'audit_status'=>3,
                //     'create_at' => time(),
                //     'update_at' => time(),
                // ];
                // PurchasePayOrderNew::create($datapay);

                //更新供应商余额
                //                [{"id": 12, "pay_money": 236595319, "order_date": "2024/04/18 00:00:00", "order_sn_code": "PO_2024041800007"}, {"id": 48, "pay_money": 82503886064, "order_date": "2024/11/16 00:00:00", "order_sn_code": "PO_2024111600006"}]

                foreach ($order_list as $item) {
                    PurchaseOrderProcess::where('order_id', '=', $item['id'])
                        ->increment('pay_real_money', $item['pay_money'], ['pay_real_time' => time()]);
                    //增加供应商余额
                    //                    Balance::changeBalance($payorderinfo->custom_id, $item['pay_money'], 2, '采购充值');
                    // Balance::purchaseRecharge($payorderinfo->custom_id, $cpid, $item['pay_money'], $manger_id);
                }
            }
            //审批记录
            DB::table('approval_histories')
                ->insert([
                    'order_id' => $id,
                    'type' => 'purchase_pay_order_approve',
                    'step_id' => $approvalinfo->current_step_id,
                    'approver_id' => $manger_id,
                    'status' => 'approved',
                ]);
            DB::commit();
        } catch (\Illuminate\Database\QueryException $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '数据库查询错误: ' . $e->getMessage()]);
        } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '模型未找到: ' . $e->getMessage()]);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核通过操作失败: ' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '审核通过']);
    }

    /**
     * 审核拒绝
     */
    public function doauditrefuse(Request $request)
    {
        $id = $request->id;

        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];

        $payorderinfo = PurchasePayOrderApprove::where([
            'id' => $id,
            'cpid' => $cpid,
        ])->first();
        if (empty($payorderinfo)) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }
        if (($payorderinfo->audit_status == 1 && $payorderinfo->approve_id1 != $manger_id) || ($payorderinfo->audit_status == 2 && $payorderinfo->approve_id2 != $manger_id)) {
            return response()->json(['code' => '001', 'msg' => '没有操作权限']);
        }
        $approvalinfo = DB::table('order_approvals')
            ->where([
                'order_id' => $id,
                'type' => 'purchase_pay_order_approve',
            ])
            ->orderBy('id', 'desc')
            ->first();

        DB::beginTransaction();
        try {

            // 所有步骤已完成
            DB::table('order_approvals')
                ->where('id', '=', $approvalinfo->id)
                ->update(['is_completed' => 1]);
            // 更新订单审批状态
            PurchasePayOrderApprove::where('id', '=', $approvalinfo->order_id)
                ->update(['audit_status' => 4]);

            //审批记录
            DB::table('approval_histories')
                ->insert([
                    'order_id' => $id,
                    'type' => 'purchase_pay_order_approve',
                    'step_id' => $approvalinfo->current_step_id,
                    'approver_id' => $manger_id,
                    'status' => 'rejected',
                ]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '审核拒绝操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '审核拒绝成功']);
    }

    /**
     * 获取付款单详情
     *
     */
    public function getinfo(Request $request)
    {
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $id = $request->id ?? 0;
        $info = PurchasePayOrderApprove::where(['cpid' => $cpid, 'is_del' => 1, 'id' => $id])
            ->where('is_tplus_sync','1')
            ->select(['order_list', 'approve_id1', 'approve_id2', 'audit_status'])
            ->with(['approver1', 'approver2'])
            ->first();

        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        // 解码 order_list
        $order_list = json_decode($info->order_list, true);

        // 预处理 order_list
        $orderIds = $order_list ? array_column($order_list, 'id') : [];

        $request->orderIds = $orderIds;
        $Purchaseorder_list = PurchaseOrder::getList($request, $cpid, 0, 1);
        //order_list 数据增加,每次付款金额
        if(isset($Purchaseorder_list['list'])){
            foreach ($Purchaseorder_list['list'] as $key1 => $purchase_item){
                foreach ($order_list as $order_list_item){
                    if($order_list_item['id'] == $purchase_item['id']){
                        $Purchaseorder_list['list'][$key1]['order_list_pay_money'] = mathfuncmoney('div',$order_list_item['pay_money'],100,2)??0;
                    }
                }
                foreach ($purchase_item['suborder'] as $key2 => $val2){
                    //历史遗留问题，此处 总重，除以1000
                    $Purchaseorder_list['list'][$key1]['suborder'][$key2]['total_weight'] = mathfuncweight('div',$val2['total_weight'],1000,4);
                    $Purchaseorder_list['list'][$key1]['suborder'][$key2]['weight'] = mathfuncweight('div',$val2['weight'],1000,4);
                    $Purchaseorder_list['list'][$key1]['suborder'][$key2]['price'] = mathfuncweight('div',$val2['price'],100,2);
                    $Purchaseorder_list['list'][$key1]['suborder'][$key2]['total_money'] = mathfuncweight('div',$val2['total_money'],100,2);
                }

            }
        }

        //审批历史
        $approvalHistories = ApprovalHistory::where('order_id', $id)
            ->where('type', 'purchase_pay_order_approve')->where('status','<>','revoked')
            ->orderBy('id', 'asc')
            ->with('approver') // 关联查询审批人信息
            ->get()
            ->map(function ($history) {
                $history->approver_name = $history->approver ? $history->approver->realname : null; // 获取审批人姓名
                return $history;
            })
            ->toArray();


        // 将审批历史放入 info 中
        $infoArray = [];
        //        $info->toArray();
        $infoArray['approval_histories'] = $approvalHistories;
        $infoArray['order_list'] = $Purchaseorder_list['list'];
        $infoArray['audit_status'] = $info->audit_status;
        // 获取 approver1 和 approver2 的 realname
        $infoArray['approver_realname'] = $approvalHistories[0]['approver_name'] ? $approvalHistories[0]['approver_name'] : null;
        $infoArray['approver1_realname'] = $info->approver1 ? $info->approver1->realname : null;
        $infoArray['approver2_realname'] = $info->approver2 ? $info->approver2->realname : null;

        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' =>  $infoArray]);
    }

    //撤审



    public function dopayrealmoney(Request $request)
    {
        $req_data = $request->only([
            'id',
            'bank_name',
            'pay_money',
            'pay_at',
            'screenshot_file',
            'remark'
        ]);

        $Validate = new PurchasePurchasePayOrderApproveSub();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        if ($this->mangerinfo['utype'] == 8) { //会计办款
            $info = PurchasePayOrderApprove::where(['cpid' => $cpid, 'is_del' => 1, 'id' => $req_data['id']])->first();
        } else { //是否需要限制只能会计办款？
            // return response()->json(['code' => '001', 'msg' => '无权限']);
            $info = PurchasePayOrderApprove::where(['cpid' => $cpid, 'is_del' => 1, 'id' => $req_data['id']])->first();
        }

        if ($info->is_finish == 1) {
            return response()->json(['code' => '001', 'msg' => '结束状态不能继续办款']);
        }


        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        if ($info->audit_status != 3) {
            return response()->json(['code' => '001', 'msg' => '审核成功方可付款']);
        }
        $req_data['pay_money']=intval(mathfuncmoney('mul',$req_data['pay_money'],100));
        // $pay_at = isset($req_data['pay_at']) ? ((strtotime($req_data['pay_at']) > 0) ? strtotime($req_data['pay_at']) : intval($req_data['pay_at'])) : 0;
        // echo $req_data['pay_money'];exit;
        $data = [
            'pid' => $req_data['id'],
            'bank_name' => $req_data['bank_name'],
            'pay_money' => $req_data['pay_money'],
            // 'pay_at' => $pay_at,
            'screenshot_file' => $req_data['screenshot_file'],
            'remark' => isset($req_data['remark'])?strval($req_data['remark']):'',
            'create_at' => time(),
            'update_at' => time(),
        ];

        //写入入库付款对账表
        // $datawp=[
        //     'cpid'=>$cpid,
        //     'manger_id'=>$info->manger_id,
        //     'type'=>2,
        //     'pay_money'=>$req_data['pay_money'],
        //     'create_at' => time(),
        //     'update_at' => time(),
        // ];

        DB::beginTransaction();
        try {
            //更新付款记录
            $PurchasePayOrderApproveSubId = PurchasePayOrderApproveSub::create($data)->id;
            //更新实际付款金额
            PurchasePayOrderApprove::where(['cpid' => $cpid, 'is_del' => 1, 'id' => $req_data['id']])->increment('pay_money_real', $data['pay_money']);
            //写入入库付款对账表
            // PurchaseWarehousingOrderwithpay::create($datawp);

            //更新供应商余额
            Balance::purchaseRecharge($info->custom_id, $cpid, $req_data['pay_money'], $this->mangerinfo['id']);

            DB::commit();
        } catch (\Exception $e) {

            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => $e->getMessage()]);
        }

        /***
         *  付款单同步
         *  1.新增 账号
         *  2.拼接名称后同步 账号【结算公司+出纳办款时返回的银行名称】 结算方式默认【网银】
         *  3.付款单(采购流) 同步 单据编号+子单据id
         *    收款单(销售流) 同步 单据编号
         *
         */
        $Chanjet_param = [
            'type' => 'purchase',
            'req_data' => $req_data,
            'PurchasePayOrderApproveSubId' => $PurchasePayOrderApproveSubId,
            'info' => $info
        ];
        $requestData = [
            "api" => "ReceivePaymentVoucherOpenApiNewCreate",
            "param" => $Chanjet_param,
            "mangerinfo" => $this->mangerinfo
        ];
        \App\Jobs\ReceiptPayment::dispatch($requestData);


//        $start_block = microtime(true);
//        if(TplusCommonController::isAllowRequestTplus($this->mangerinfo)) { //付款单
//
//            /**
//             *  创建账号
//             *  使用华坤系统的 结算公司+办款银行 拼音 作为 账号的code创建
//             *
//            **/
//            $BankAccountCode = common::getPinyin($info["pa_settle_company_name"]).'_'.common::getPinyin($req_data['bank_name']);
//            $BankAccountName = $info["pa_settle_company_name"].'_'.$req_data['bank_name'];
//            TplusCommonController::createBankAccount($BankAccountCode,$BankAccountName,$this->mangerinfo["org_id"]);
//
//            //创建结算方式  固定 网银
//            $SettleStyleCode = TplusCommonController::getSettleStyle($this->mangerinfo["org_id"]);
//
//            $Chanjet_param = [
//                "dto" => [
//                    "VoucherDate" => date('Y-m-d'),
//                    "Code" => $info['pay_sn_code'].'|'.$PurchasePayOrderApproveSubId,//付款单单据编号 +sub单据id
//                    "IsModifiedCode" => "true",
//                    "ExternalCode" => $info['pay_sn_code'].'|'.$PurchasePayOrderApproveSubId,
//                    "Partner" => [
//                        "Code" => Custom::where('id',$info["custom_id"])->value("company_code"),
//                    ],
//                    //往来单位编码
//                    "Department" => ["Code" => strval($this->mangerinfo["sys_dpm_id"])],//部门
//                    "IsReceiveFlag" => "false",//赋值为true，则为收款单;赋值为false，则为付款单
//                    "BusiType" => ["Code"=>"36"],//付款单时，包括35（普通付款），36（预付款）和46（直接付款）；
//                    "ArapMultiSettleDetails" => [ //多结算明细
//                        [
//                            "SettleStyle" => ["code" => $SettleStyleCode],//网银code
//                            "BankAccount" => ["name" => $BankAccountName],
//                            "OrigAmount" => strval($req_data['pay_money']/100),
//                        ]
//                    ]
//                ]
//            ];
//            ChanjetRequest::getInstance()->ReceivePaymentVoucherOpenApiNewCreate($Chanjet_param,$this->mangerinfo['org_id']);
//
//        }
//        $time_block = microtime(true)- $start_block;
//        Log::info("同步付款单,time: ".$time_block);

        return response()->json(['code' => '000', 'msg' => '办款成功']);
    }

    public function getPayOrderApproveList(Request $request)
    {
        $cpid = $this->mangerinfo['cpid'];
        $id = $request->id ?? 0;
        $info = PurchasePayOrderApprove::where(['cpid' => $cpid, 'is_del' => 1, 'id' => $id])
            ->first();

        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        $paysublist = PurchasePayOrderApproveSub::where(['pid' => $id])->get();




        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => ['info' => $info, 'paysublist' => $paysublist]]);
    }



    /**
     * 结束办款
     */
    public function dofinish(Request $request)
    {
        $id = $request->id;

        $cpid = $this->mangerinfo['cpid'];

        $payorderinfo = PurchasePayOrderApprove::where([
            'id' => $id,
            'cpid' => $cpid,
        ])->first();
        if (empty($payorderinfo)) {
            return response()->json(['code' => '001', 'msg' => '订单不存在']);
        }

        DB::beginTransaction();
        try {

            PurchasePayOrderApprove::where([
                'id' => $id,
                'cpid' => $cpid,
            ])->update(['is_finish'=>1]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '结束操作失败' . $e->getMessage()]);
        }
        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }


}
